import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { loginAPI } from '@/api/user'

export const useUserStore = defineStore('user', () => {
    const nickname = ref('')
    const role = ref('')
    const token = ref('')

    const login = async (username: string, password: string, remember: boolean) => {
        try {
            const { username: resNickname, role: resRole, token: resToken } = await loginAPI({ username, password })
            if (remember) {
                localStorage.setItem('username', username)
            } else {
                localStorage.removeItem('username')
            }

            nickname.value = resNickname
            role.value = resRole
            token.value = resToken

            return true
        } catch (error) {
            console.log(error)
            return false
        }
    }

    const logout = () => {
        nickname.value = ''
        role.value = ''
        token.value = ''
    }

    return {
        nickname,
        role,
        token,
        login,
        logout,
    }

}, {
    persist: {
        key: 'user',
        storage: localStorage,
        pick: ['token', 'nickname', 'role'],
        debug: true,
    }
})